<template>
  <view class="container" @click="handleWrapperClick">
    <!-- 左侧人物聊天框 -->
    <view class="sidebar">
      <!-- 头部 -->
      <view class="sidebar-header">
        <text class="header-title">对话窗口</text>
        <view class="header-right">
          <image 
            src="/static/search-icon.png" 
            class="search-icon" 
            @click="openSearch()" 
          />
        </view>
      </view>

      <!-- 人物对话选择 -->
      <scroll-view 
        class="chat-list"
        scroll-y
        :scroll-into-view="scrollToUserView"
      >
        <view 
          v-for="(chat, index) in chatList" 
          :key="chat.id"
          :id="'user-' + chat.id" 
          class="chat-item"
          :class="{ 
            'selected': selectedChat === chat, 
            'last-item': index === chatList.length - 1 
          }"
          @click="selectChat(chat,'userChat')"
        >
         
          <!-- 头像容器（增加红点标记位置） -->
             <view class="avatar-container">
               <image 
                 class="avatar" 
                 :src="chat.avatar || defaultAvatar"
                 mode="aspectFill"
                 @error="handleAvatarError"
               />
               <!-- 新消息红点 -->
               <view 
                 v-if="chat.readed" 
                 class="red-dot"
               ></view>
             </view>
		  
		
          <view class="chat-content">
            <text class="chat-name">{{ chat.name }}</text>
            <text 
              class="last-message" 
              v-if="chat.messages.length !== 0"
            >
              {{ chat.messages[chat.messages.length-1].msg.split('\n')[0] }}
            </text>
          </view>
		  
		  <!-- 身份标识（最右侧） -->
		    <view class="identity-badge" :class="'role-' + (chat.roleType || 1)">
		      <text v-if="chat.roleType === 2">导</text>
		      <text v-else-if="chat.roleType === 3">咨</text>
		      <text v-else-if="chat.roleType === 1">学</text>
			  <text v-else>未</text>
		    </view>
        </view>
      </scroll-view>

      <!-- 底部个人信息 -->
      <view class="user-panel">
        <view class="user-info">
          <image 
            class="user-avatar" 
            :src="getAvatarSrc(userInfo.avatar)"
            @error="handleAvatarError"
            mode="aspectFill"
          />
          <text class="user-name">{{ userInfo.name }}</text>
        </view>
        <image 
          class="settings-icon" 
          src="/static/settings-icon.png" 
          @click="openSettings"
        />
      </view>
    </view>

    <!-- 右侧对话窗口 -->
    <view class="chat-window">
      <!-- 消息列表 -->
      <scroll-view 
        class="messages" 
        scroll-y 
        :style="{ height: msgsHeight + 'px' }"
        :scroll-into-view="scrollToView"
      >
        <view v-if="selectedChat">
          <view 
            v-for="(item,index) in selectedChat.messages" 
            class="message-container"
            :key="item.id"
            :class="[
              item.show ? 'other-message' : 'self-message',
              { 'selected': selectedMessageId === item.id }
            ]"
            @click="handleClick(item.id, $event)"
            @dblclick="handleDoubleClick(item.id, $event)"
            :id="'item-' + item.id" 
          >
            <!-- 对方消息 -->
            <template v-if="item.show">
              <image 
                class="avatar left-avatar" 
                :src="getAvatarSrc(selectedChat.avatar)" 
                @error="handleAvatarError"
              />
              <view class="message-content left-content">
                <view class="bubble left-bubble">
                  <text>{{ item.msg }}</text>
                  <view class="timestamp">{{ item.timestamp }}</view>
                </view>
                <!-- 菜单（水平排列） -->
                <view 
                  v-if="selectedMessageId===item.id" 
                  class="context-menu horizontal-menu"
                  @click.stop
                >
                  <view class="menu-item" @click="deleteSelectedMessage">删除</view>
                  <view class="menu-item" @click="closeContextMenu">取消</view>
                </view>
              </view>
            </template>
          
            <!-- 自己消息 -->
            <template v-else>
              <view class="message-content right-content">
                <view class="bubble right-bubble">
                  <text>{{ item.msg }}</text>
                  <view class="status-wrapper">
                    <text class="timestamp">{{ item.timestamp }}</text>
                    <text class="status-icon">
                      {{ item.status === 1 ? '✓' : item.status === 2 ? '✓✓' : '🕒' }}
                    </text>
                  </view>
                </view>
                <!-- 菜单（水平排列） -->
                <view 
                  v-if="selectedMessageId===item.id" 
                  class="context-menu horizontal-menu"
                  @click.stop
                >
                  <view class="menu-item" @click="deleteSelectedMessage">删除</view>
                  <view class="menu-item" @click="closeContextMenu">取消</view>
                </view>
              </view>
              <image 
                class="avatar right-avatar"  
                :src="getAvatarSrc(userInfo.avatar)" 
                @error="handleAvatarError"
              />
            </template>
          </view>
        </view>
      </scroll-view>

      <!-- 输入区域 -->
      <view class="editor-box">
        <view class="editor-container">
          <!-- 编辑区 -->
          <view class="editor-content" scroll-y>
            <textarea 
              scroll-y
              v-model="newMessage" 
              placeholder="请输入内容..." 
              class="text-editor"
            />
          </view>
          
          <!-- 操作栏 -->
          <view class="editor-actions">
            <view class="action-group">
              <view class="icon-btn" @click="clearChatList()">
                <image src="/static/attach.png" class="action-icon" mode="aspectFit" />
                <text class="btn-text">文件</text>
              </view>
              
              <view class="more-actions">
                <view class="icon-btn" @click="chooseImage">
                  <image src="/static/image.png" class="action-icon" mode="aspectFit" />
                  <text class="btn-text">图片</text>
                </view>
                <view class="icon-btn" @click="showEmojiPicker">
                  <image src="/static/emoji.png" class="action-icon" mode="aspectFit" />
                  <text class="btn-text">表情</text>
                </view>
                <view class="icon-btn" @click="searchChat">
                  <image src="/static/chat.png" class="action-icon" mode="aspectFit" />
                  <text class="btn-text">记录</text>
                </view>
				<view class="icon-btn" @click="toggleAnonymous">
				  <image  :src="isAnonymous ? '/static/anonymous-active.png' : '/static/anonymous.png'"  class="action-icon" mode="aspectFit" />
				  <text class="btn-text">匿名</text>
				</view>
				
              </view>
            </view>
          
            <button 
              class="send-btn" 
              :class="{ disabled: !canSend }" 
              @click="sendMessage"
            >
              {{ sending ? '发送中...' : '发送' }}
            </button>
          </view>
        </view>
      </view>
    </view>
  
    <!-- 开启用户搜索框 -->
    <view 
      :class="[
        'search-folder-modal', 
        { 
          'slide-in': showSearchModal, 
          'slide-out': !showSearchModal 
        }
      ]" 
      @click="closeSearch"
    >
      <view class="modal-content" @click.stop>
        <!-- 搜索模式切换 -->
        <view class="search-tabs">
          <text 
            :class="[
              'tab-item', 
              { 'active': searchMode === 'local' }
            ]"
            @click="switchSearchMode('local')"
          >
            本地对话
          </text>
          <text 
            :class="[
              'tab-item', 
              { 'active': searchMode === 'network' }
            ]"
            @click="switchSearchMode('network')"
          >
            网络搜索
          </text>
        </view>
        
        <!-- 搜索框 -->
        <view class="search-bar">
          <input
            class="search-input"
            v-model="searchKeyword"
            :disabled="isSearching"
            :class="{ 'icon-disabled': isSearching }"
            placeholder="搜索对话或网络内容"
          />
          <image 
            src="/static/search-icon.png" 
            class="search-icon" 
            @click="handleManualSearch"
          />
        </view>
        
        <!-- 搜索结果区域 -->
        <scroll-view scroll-y class="result-container">
          <!-- 加载状态 -->
          <view v-if="isSearching" class="loading-state">
            <text>搜索中...</text>
          </view>
          
          <!-- 本地搜索结果 -->
          <template v-else-if="searchMode === 'local' && hasSearched">
            <view 
              v-for="chat in localResults"
              :key="chat.id"
              class="chat-item"
              @click="selectChat(chat)"
            >
              <image class="avatar" :src="getAvatarSrc(chat.avatar)"/>
              <view class="chat-info">
                <text class="chat-name">{{ chat.name }}</text>
              </view>
              <!-- 右侧删除按钮 -->
              <view 
                class="delete-btn" 
                @click.stop="deleteChat(chat.id)"
              >
                <text>删除</text>
              </view>
            </view>

            <view v-if="localResults.length === 0" class="empty-tips">
              未找到匹配的对话
            </view>
          </template>
          
          <!-- 网络搜索结果 -->
          <template v-else-if="searchMode === 'network'&&  hasSearched">
               <view
                 v-for="chat in networkResults"
                 :key="chat.id"
                 class="network-chat-item"
               >
                 <!-- 左侧身份标识 -->
                 <view class="identity-badge" :class="'role-' + (chat.roleType || 0)">
                   <text>{{ getRoleBadgeText(chat.roleType) }}</text>
                 </view>
             
                 <!-- 头像 -->
                 <image class="network-avatar" :src="getAvatarSrc(chat.avatar)" mode="aspectFill"/>
             
                 <!-- 主体信息 -->
                 <view class="network-info">
                   <view class="name-line">
                     <text class="network-name">{{ chat.name }}</text>
                     <text class="network-role">{{ getRoleText(chat.roleType) }}</text>
                   </view>
                   <text class="network-id">ID: {{ chat.id }}</text>
                 </view>
             
                 <!-- 右侧操作按钮 -->
                 <view 
                   class="network-action"
                   :class="{ 'exists': isChatExist(chat.id) }"
                   @click.stop="handleAddChat(chat)"
                 >
                   <image 
                     v-if="!isChatExist(chat.id)" 
                     src="/static/add-contact.png" 
                     class="action-icon"
                   />
                   <image 
                     v-else
                     src="/static/checkmark.png" 
                     class="action-icon"
                   />
                 </view>
               </view>
            <view v-if="networkResults.length === 0" class="empty-tips">
              未找到相关网络结果
            </view>
          </template>
        </scroll-view>
      </view>
    </view>
    
    <!-- 开启用户聊天记录框 -->
    <view 
      :class="[
        'search-chat-folder-modal', 
        { 
          'slide-in': searchChatModel, 
          'slide-out': !searchChatModel 
        }
      ]" 
      @click="closeSearchChat"
    >
      <view class="modal-content" @click.stop>
        <!-- 搜索框 -->
        <view class="search-bar">
          <input
            class="search-input"
            v-model="keyword"
            placeholder="搜索聊天记录"
          />
          <image 
            src="/static/search-icon.png" 
            class="search-icon" 
            @click="startSearch"
            :class="{ 'icon-disabled': searching }"
          />
        </view>
        
        <!-- 搜索结果 -->
        <scroll-view scroll-y class="result-container">
          <!-- 加载状态 -->
          <view v-if="loading" class="loading">
            <text>搜索中...</text>
          </view>
          
          <!-- 搜索结果 -->
          <template v-else-if="searchResults.length > 0">
            <view 
              v-for="(group, date) in groupedResults" 
              :key="date" 
              class="date-group"
            >
              <view class="date-title">{{ formatGroupDate(date) }}</view>
              
              <view 
                v-for="msg in group" 
                :key="msg.id" 
                class="message-item" 
                @click="selectMessage(msg.id)"
              >
                <view 
                  class="message-content" 
                  :class="{'self-message': !msg.show}"
                >
                  <view class="message-header">
                    <text class="sender">{{ msg.show ? selectedChat.name : '我' }}</text>
                    <text class="time">{{ formatTime(msg.timestamp) }}</text>
                  </view>
                  <text 
                    class="message-text" 
                    v-html="highlightKeyword(msg.msg)"
                  ></text>
                </view>
              </view>
            </view>
          </template>
          
          <!-- 空状态 -->
          <view v-else-if="searched" class="empty">
            <text>没有找到匹配的聊天记录</text>
          </view>
          
          <!-- 初始状态 -->
          <view v-else class="initial-hint">
            <text>输入关键词搜索聊天记录</text>
          </view>
        </scroll-view>
      </view>
    </view>
	
	
  </view>
</template>

<script>
import methodY from '@/util/methodY.js';
import { mapState } from 'vuex';
export default {
	data() {
	  return {
		  
		  default_avatar: '/static/default-avatar.jpeg',
		  msgsHeight: 0,          // 消息列表的自适应高度
		  scrollToView: "",       // 到达消息底部
		  scrollToUserView: "",   // 左侧用户
		  userInfo: {
			id:'',
		    avatar: "/static/logo.png",
		    name: "徐海东"
		  },
		  chatList: [],
		  selectedChat: null,
		  newMessage: '',
		  sending: false,
		  
		  // 用户搜索框相关
		  showSearchModal: false,
		  searchMode: 'local',    // local | network
		  searchKeyword: '',
		  localResults: [],
		  networkResults: [
			  
		  ],
		  isSearching: false,     // 是否正在搜索
		  hasSearched: false,     // 是否已完成搜索
		  
		  // 聊天记录相关
		  searchChatModel: false,
		  searchQuery: '',
		  keyword: '',
		  searching: false,
		  searched: false,
		  searchResults: [],
		  
		  // 消息菜单栏相关
		  selectedMessageId: null, // 当前选中的消息ID
		  lastClickTime: 0,
		  longPressTimer: null,
		  //匿名
		   isAnonymous: false, // 匿名状态
		   anonymousKey:undefined,
		   
	  };
	},
    async mounted() {
     	this.handleMsgsHeightChange();
		const userInfo = methodY.util.getUserInfo() || {};
		const userId = userInfo.userId;
		this.userInfo.id=userId;
    	this.loadChatList();
		this.handleWebSocketReconnect();
		this.anonymousKey=this.initAnonymousId();
		console.log("用户id  anonymousKey",userId,this.anonymousKey);
     },
    computed: {
		...mapState(['webSocketConnected',"msg"]),
        canSend() {
         return this.newMessage.trim() !== "" &&this.selectedChat!=null &&!this.sending ;
        },
    	// 按日期分组的结果
    	groupedResults() {
    	  const groups = {}
    	  this.searchResults.forEach(msg => {
    	    // 提取年月日作为分组key (格式: 2024-02-20)
    	    const dateKey = msg.timestamp.split(' ')[0]
    	    
    	    if (!groups[dateKey]) {
    	      groups[dateKey] = []
    	    }
    	    groups[dateKey].push(msg)
    	  })
    	  return groups
    	}
     },
	watch: {
		
	    webSocketConnected(newVal, oldVal) {
	        console.log('count changed from ' + oldVal + ' to ' + newVal);
	        // 这里你可以根据新的值进行相应的操作
	     },
		  // 监听 msg 对象的变化
		msg: {
		    handler(newVal, oldVal) {
		        console.log('msg changed:', newVal);
		        // 这里可以执行相应的操作
				let sign=newVal.msgData.msg;
				let data=newVal.msgData.data;
				let code=newVal.msgData.code;
				if("SEND_MSG"===sign){
					//1.如果是正常消息的发送
					//console.log(data);
					this.handleNewMessages(data);
				}
				if("send_msg_ok"===sign){
					const data1 = JSON.parse(data);
					this.updateMessageStatus(data1.receiver, data1.tempId, 1); // 更新为已送达
					
				}
				if("ANONYMOUS_MSG"===sign){
					this.handleNewMessages(data,sign);
				}
				if("MSG"===sign){
					this.handleNewMessages(data,sign);
				}
		    },
		    deep: true // 深度监听
		},
	    searchKeyword(newVal, oldVal) {
	      if (!newVal && !this.isSearching && this.hasSearched) {
	        this.hasSearched = false
	        this.clearResults()
	      }
	    },
			
		// 监听关键词变化
		keyword(newVal) {
		  if (!newVal.trim()) {
		    this.searchResults=[]
		  }
		}
	 },
    methods: {
		 // 检查聊天是否已存在
		    isChatExist(chatId) {
		      return this.chatList.some(chat => chat.id === chatId);
		    },
		    
		    // 处理添加聊天
		    handleAddChat(chat) {
			  if(chat.id===this.userInfo.id){
				uni.showToast({ title: '该聊天不可存在', icon: 'none' });
				return;
			  }
		      if (this.isChatExist(chat.id)) {
		        uni.showToast({ title: '该聊天已存在', icon: 'none' });
		        return;
		      }
		      
		      const newChat = {
		        id: chat.id,
		        name: chat.name,
		        roleType: chat.roleType || 0,
		        avatar: chat.avatar,
		        readed: false,
		        msgListKey: 0,
		        messages: [] // 初始空消息
		      };
		      
		      this.chatList.unshift(newChat);
		      this.saveChatList();
		      uni.showToast({ title: '添加成功', icon: 'success' });
		    },
		    
		    // 身份标识文本
		    getRoleBadgeText(roleType) {
		      const roles = {
		        0: '未',
		        1: '学',
		        2: '导',
		        3: '咨'
		      };
		      return roles[roleType] || '未';
		    },
		    
		    // 身份描述文本
		    getRoleText(roleType) {
		      const roles = {
		        0: '未设置身份',
		        1: '学生',
		        2: '辅导员',
		        3: '咨询师'
		      };
		      return roles[roleType] || '未知身份';
		    },
		// 切换匿名状态
		toggleAnonymous() {
		  this.isAnonymous = !this.isAnonymous;
		  uni.showToast({
		    title: this.isAnonymous ? '已开启匿名' : '已关闭匿名',
		    icon: 'none'
		  });
		},
		 initAnonymousId() {
		    // 尝试从缓存读取已有ID
		    const cachedId = uni.getStorageSync('anonymousKey'+this.userInfo.id)
		    if (cachedId) return cachedId
		    // 生成新ID并缓存
		    // const newId = `anon_${}_${Date.now().toString(36)}`
		   this.saveAnonymousCount(0);
		    return 0
		  },
		// 获取当前匿名序号（从缓存）
		  getAnonymousCount() {
		    try {
		      return uni.getStorageSync('anonymousKey'+this.userInfo.id) || 0
		    } catch (e) {
		      console.error('读取匿名序号失败:', e)
		      return 0
		    }
		  },
		  // 缓存匿名序号
		  saveAnonymousCount(newCount) {
		    uni.setStorageSync('anonymousKey'+this.userInfo.id, newCount)
		  },
		 // 更新特定消息的状态
		  updateMessageStatus(receiverId, tempId,newStatus) {
		    // 1. 找到对应的聊天
		    const chat = this.chatList.find(
		      chat => chat.id === receiverId
		    );
		    
		    if (!chat) {
		      console.warn(`未找到receiverId=${receiverId}的聊天`);
		      return;
		    }
		
		    // 2. 找到临时消息
		    const message = chat.messages.find(
		      msg => msg.id.toString() === tempId
		    );
		    
		    if (!message) {
		      console.warn(`未找到tempId=${tempId}的消息`);
		      return;
		    }
		
		    // 3. 更新状态（确保响应式）
		    this.$set(message, 'status', newStatus);
		    this.saveChatList();
		  },
	   // 处理新消息
	      handleNewMessages(newMessages,sign) {
			  console.log("处理新消息",Array.isArray(newMessages),newMessages,typeof newMessages === 'string')
			// 1. 参数标准化（确保是数组） 
			const messages = JSON.parse(newMessages);
			
	       messages.forEach(msg => {
			   if(sign==="MSG"){
			   		//修改为
			   		if(msg.sign==="true"){
			   			sign= "ANONYMOUS_MSG"
			   		}else{
			   			sign= "SEND_MSG"
			   		}
			   }
	          const chatIndex = this.findChatIndex(msg,sign);
	          
	          if (chatIndex >= 0) {
				console.log("新消息更新")
	            this.updateExistingChat(chatIndex, msg,sign);
				if(this.selectedChat.id===msg.sender||this.selectedChat.id==='anonymous_'+msg.sender){
					this.selectedChat.readed=false;
					console.log("新消息更新跳底部");
					this.scrollToBottom(this.selectedChat.id);
				}
	          } else {
				console.log("新消息需要创建",msg)
	            this.createNewChat(msg,sign);
	          }
			  
	        });
			this.saveChatList();
			console.log("新的聊天列表为:",this.chatList);
	      },
		   // 查找匹配的聊天
		findChatIndex(msg,sign) {
			let sender=msg.sender;
			if("ANONYMOUS_MSG"===sign){
				sender= 'anonymous_'+msg.sender
			}
		  return this.chatList.findIndex(chat => 
		    chat.id === sender
		  );
		},
		 // 更新现有聊天
		    updateExistingChat(index, newMsg,sign) {
		      const chat = this.chatList[index]
		      console.log("正在跟新",sign)
		      // 更新聊天信息
		      chat.name = newMsg.name || chat.name
		      chat.avatar = methodY.addr+newMsg.avatar_path || chat.avatar
		      chat.readed=true;
			  if(newMsg.auth==="1"){
				chat.roleType=1
			  }else if(newMsg.auth==="2"){
				chat.roleType=2
			  }else if(newMsg.auth==="3"){
				chat.roleType=3
			  }else{
				chat.roleType=0
			  }
			  
		      // 添加新消息
		      chat.messages.push({
		        id: chat.msgListKey ,  
		        timestamp: newMsg.timestamp,
		        show: true,               // 固定为true
		        msg: newMsg.content,
		        status: 1
		      })
		      
		      // 更新msgListKey
		      chat.msgListKey -= 1
		    },
		    
		    // 创建新聊天
		    createNewChat(newMsg,sign) {
				console.log("正在创建",sign)
				let roleType=1
			   if(newMsg.auth==="1"){
			   	  roleType=1
			   }else if(newMsg.auth==="2"){
			   		roleType=2
			   }else if(newMsg.auth==="3"){
				roleType=3
			  }else{
				roleType=0
			  }
			  
			 let sender=newMsg.sender;
			 if("ANONYMOUS_MSG"===sign){
			 	sender= 'anonymous_'+newMsg.sender
			 }
		      this.chatList.push({
		        id: sender,
				readed:true,
				roleType:roleType,
		        name:  `匿名用户_${this.anonymousKey}_${Date.now().toString(36).substr(0, 4)}`,
		        avatar:methodY.addr+newMsg.avatar_path,
		        msgListKey: -1,  // 初始值
		        messages: [{
		          id: 0,        // msgListKey-1
		          timestamp: newMsg.timestamp,
		          show: true,
		          msg: newMsg.content,
		          status: 1
		        }]
		      })
			  this.anonymousKey=this.anonymousKey+1;
			  this.saveAnonymousCount(this.anonymousKey);
		    },
			
	  handleWebSocketReconnect() {
	    try {
	      // 1. 获取WebSocket URL中的ID参数
	      const wsUrl = this.$socket?.url || '';
	      const queryString = wsUrl.split('?')[1] || '';
	      const params = new URLSearchParams(queryString);
	      const socketId = params.get('id'); // 从URL提取的ID
	  
	      // 2. 获取当前用户ID
	      const userInfo = methodY.util.getUserInfo() || {};
	      const userId = userInfo.userId;
		  this.userInfo.id=userId;
	      // 3. 验证逻辑
	      if (typeof userId === 'undefined') {
	        // 情况1：用户未登录
			 uni.showModal({
			    title: '未登录',
			    content: '请先登录',
			    confirmText: '去登录',
			    success: (res) => {
			        if (res.confirm) {
			            methodY.util.backToIndex();
			        }
			    }
			});
	        return;
	      }
	      if (userId !== socketId) {
			
	        // 情况2：ID不匹配，需要重新连接
	         uni.showLoading({
	                title: '正在重新连接...',
	                mask: true // 防止用户操作
	         });
			 this.$socket.url=methodY.wsAddr+"/ws?id="+userId;
			 this.$socket.close()
			  // 3秒后关闭 loading
			setTimeout(() => {
			    uni.hideLoading();
			}, 3000);
	      } else {
	        // 情况3：正常连接
	        console.log('WebSocket连接正常', { socketId, userId });
	      }
	  
	    } catch (error) {
	      console.error('WebSocket连接检查失败:', error);
	    }
	  },
      // 保存聊天列表到缓存
      saveChatListToStorage(chatList) {
        try {
          uni.setStorageSync('chatList'+this.userInfo.id, JSON.stringify(chatList));
          console.log('聊天列表已保存到本地存储');
        } catch (e) {
          console.error('保存聊天列表失败:', e);
        }
      },
    
      // 从缓存读取聊天列表
      getChatListFromStorage() {
        try {
          const chatListStr = uni.getStorageSync('chatList'+this.userInfo.id);
          return chatListStr ? JSON.parse(chatListStr) : [];
        } catch (e) {
          console.error('读取聊天列表失败:', e);
          return [];
        }
      },
	  
	  // 删除聊天列表缓存
	    clearChatList() {
	      try {
	        uni.removeStorageSync('chatList'+this.userInfo.id);
	        return true;
	      } catch (e) {
	        console.error('删除聊天列表失败:', e);
	        return false;
	      }
	    },
      // 从缓存加载聊天列表
      loadChatList() {
        this.chatList = this.getChatListFromStorage();
        
        // 如果缓存为空，使用默认数据
        if (this.chatList.length === 0) {
          this.chatList = [
            { 
              id: 1,
              name: "Chat 1",
			  readed:false,
			  roleType:0,
              avatar: "http://localhost:80/static/avatars/2.jpg",
              msgListKey: 0,
              messages: [
                {
                  id: -888,
                  timestamp: "2024-2-20",
                  show: true, // 代表对话人
                  msg: "你么积极啊急急急啊哈哈哈",
                  status: 1
                },
                {
                  id: -999,
                  timestamp: "2024-2-20",
                  show: false, // 代表自己
                  msg: "你么么uuu",
                  status: 1
                }
              ]
            },
            { 
              id: 2,
              name: "Chat 2",
			  roleType:2,
			  readed:true,
              avatar: "/static/changli_com.jpg",
              msgListKey: 0,
              messages: [
                {
                  id: -667,
                  timestamp: "2024-2-20",
                  show: true,
                  msg: "你么积极啊急急急啊哈哈哈你么积极啊急急急啊哈哈哈你么积极啊急急急啊哈哈哈",
                  status: 1
                },
                {
                  id: -999,
                  timestamp: "2024-2-20",
                  show: false,
                  msg: "你",
                  status: 1
                }
              ]
            },
            { id: 3, roleType:3,readed:true,name: "Chat 2", avatar: "/static/changli_com.jpg", msgListKey: 0, messages: [] },
            { id: 4,roleType:1,readed:true, name: "Chat gg", avatar: "/static/changli_com.jpg", msgListKey: 0, messages: [] },
            { id: 5,roleType:1,readed:true, name: "Chat hah", avatar: "/static/changli_com.jpg", msgListKey: 0, messages: [] },
            { id: 6, roleType:1,readed:true,name: "Chat 88", avatar: "/static/changli_com.jpg", msgListKey: 0, messages: [] },
            { id: 7,roleType:2,readed:true, name: "Chat nn", avatar: "/static/changli_com.jpg", msgListKey: 0, messages: [] },
            { id: 8,roleType:3,readed:true, name: "Chat 11", avatar: "/static/changli_com.jpg", msgListKey: 0, messages: [] },
            { id: 9, roleType:1,readed:true,name: "Chat ahh", avatar: "/static/changli_com.jpg", msgListKey: 0, messages: [] },
            { id: 10,roleType:1,readed:true, name: "Chat 777", avatar: "/static/changli_com.jpg", msgListKey: 0, messages: [] },
            { id: 11,roleType:1,readed:true, name: "Chat 1", avatar: "/static/changli_com.jpg", msgListKey: 0, messages: [] },
            { id: 12,roleType:1, readed:true,name: "Chat h", avatar: "/static/changli_com.jpg", msgListKey: 0, messages: [] },
            { id: 13,roleType:1,readed:false,name: "Chat 7", avatar: "/static/changli_com.jpg", msgListKey: 0, messages: [] }
          ];
          this.saveChatList();
        }
      },
      
      // 保存当前聊天列表到缓存
      saveChatList() {
        this.saveChatListToStorage(this.chatList);
      },
      
      // 添加新聊天
      addNewChat(chat) {
        this.chatList.unshift(chat); // 添加到列表开头
        this.saveChatList();
      },
      
      // 更新特定聊天
      updateChat(chatId, newData) {
        const index = this.chatList.findIndex(c => c.id === chatId);
        if (index !== -1) {
          this.chatList[index] = { ...this.chatList[index], ...newData };
          this.saveChatList();
        }
      },
      
      // 删除聊天
      deleteChat(id) {
        uni.showModal({
          title: '确认删除',
          content: '确定删除此聊天记录吗？',
          success: (res) => {
            if (res.confirm) {
              const index = this.localResults.findIndex(c => c.id === id);
              if (index !== -1) {
                this.localResults.splice(index, 1);
                this.chatList = this.chatList.filter(c => c.id !== id);
                console.log(this.chatList);
                this.saveChatList();
              }
            }
          }
        });
      },
      
      // 点击处理（兼容单击/双击）
      handleClick(id) {
        const now = Date.now();
        const DOUBLE_CLICK_DELAY = 300; // 双击间隔300ms
        
        if (now - this.lastClickTime < DOUBLE_CLICK_DELAY) {
          clearTimeout(this.longPressTimer);
          this.selectMessage1(id);
        }
        
        this.lastClickTime = now;
      },
      
      // 双击处理（显示菜单）
      handleDoubleClick(id, e) {
        this.selectedMessageId = id;
        clearTimeout(this.longPressTimer);
      },
      
      handleWrapperClick() {
        this.selectedMessageId = null;
      },
      
      // 删除消息
      deleteSelectedMessage() {
        uni.showModal({
          title: '确认删除',
          content: '确定要删除这条消息吗？',
          success: (res) => {
            if (res.confirm) {
              const index = this.selectedChat.messages.findIndex(
                msg => msg.id === this.selectedMessageId
              );
              if (index !== -1) {
                // 实际删除操作
                this.selectedChat.messages.splice(index, 1);
                this.saveChatList();
                uni.showToast({ title: '已删除', icon: 'success' });
              }
            }
            this.closeContextMenu();
          }
        });
      },
      
      // 关闭菜单
      closeContextMenu() {
        this.selectedMessageId = null;
      },
      
      getAvatarSrc(avatarPath) {
        return avatarPath || this.default_avatar;
      },
      
      // 图片加载错误处理
      handleAvatarError(e) {
        e.target.src = this.default_avatar;
      },
      
      // 滑到底部
      scrollToBottom(id) {
        this.$nextTick(() => {
          setTimeout(() => {
            this.scrollToView = 'item-' + String(id);
            console.log(this.scrollToView);
          }, 100); // 调整延迟时间
        });
      },
      
      handleMsgsHeightChange() {
        uni.getSystemInfo({
          success: (info) => {
            console.log('屏幕的高度：' + info.windowHeight);
            const query = uni.createSelectorQuery().in(this);
            query.select('.input-area').boundingClientRect(data => {
              if (data) {
                this.msgsHeight = info.windowHeight - data.height - info.statusBarHeight;
              }
            }).exec();
          }
        });
      },
      
      // 选中对话人
      selectChat(chat, model) {
        this.selectedChat = chat;
        console.log("userChat" != model);
        chat.readed=false;
        if (this.selectedChat.id != null && "userChat" != model) {
          // 右侧导航栏也是
          this.$nextTick(() => {
            setTimeout(() => {
              this.scrollToUserView = 'user-' + String(this.selectedChat.id);
              console.log(this.scrollToUserView);
            }, 100); // 调整延迟时间
          });
        }
        
        // 切换对话聊天会滑到底部
        const getLastMessageId = (chat) => {
          if (!chat.messages || chat.messages.length === 0) {
            return null; // 或者返回一个默认值
          }
          return chat.messages[chat.messages.length - 1].id;
        };
        
        const lastMessageId = getLastMessageId(this.selectedChat);
        console.log(lastMessageId);
        if (lastMessageId != null) {
          this.scrollToBottom(lastMessageId);
        }
      },
      // getMessageReceiver() {
      //   // 获取基础接收者ID
      //   let receiver = this.selectedChat.id;
        
      //   // 如果是匿名模式且接收者ID包含'anonymous_'前缀
      //   if (!this.isAnonymous && receiver.startsWith('anonymous_')) {
      //     // 移除前缀（示例：anonymous_123 → 123）
      //     receiver = receiver.replace(/^anonymous_/, '');
      //   }
        
      //   return receiver;
      // },
      sendMessage() {
        if (this.selectedChat && this.newMessage.trim() !== '') {
          // 点击发送数据 先生成对象 {user_from的账号，user_to的账号, 发送消息,时间,show}
          let curTime = this.getCurrentTime();
          let msgText = this.newMessage.trim();
          let id = this.selectedChat.msgListKey--;
          
          let msgShow = {
            id: id,
            timestamp: curTime,
            show: false,
            msg: msgText,
            status: 0,
            showLeftButton: false
          };
          
          this.selectedChat.messages.push(msgShow);
          this.scrollToBottom(id); // 每次添加消息后调用 跳转到最后面
		  // {
		  //   "text": {
		  //     "msg": "SEND_MSG",
		  //     "data": {
		  //       "content": "你好123，这是一条消息1001",
		  //       "sender": "1234",
		  //       "receiver":"123",
		  //       "timestamp": "2023-08-20 11:30:59"
		  //     }
		  //   }
		  // }
	
		   // 3. 构建WebSocket消息
		  
		      const wsMsg = {
		        text: {
		          msg: this.isAnonymous ?"ANONYMOUS_MSG":"SEND_MSG",
		          data: {
		            content: msgText,
		            sender: this.userInfo.id, // 当前用户ID
		            receiver: this.selectedChat.id, // 对方ID
		            timestamp: curTime,
		            tempId: String(id) // 本地临时ID（用于消息状态更新）
		          }
		        }
		      };
			
		  this.$socket.send(JSON.stringify(wsMsg)) //正常发送信息
          this.saveChatList();
          this.newMessage = '';
        }
      },
      
      openSettings() {
        // 打开设置
      },
      
      switchSearchMode(mode) {
        this.searchMode = mode;
        this.hasSearched = false;
        this.isSearching = false; // 是否正在搜索
        this.localResults = [];
        this.networkResults = [];
      },
      
      // 清空结果
      clearResults() {
        this.localResults = [];
        this.networkResults = [];
      },
      
      async handleManualSearch() {
        if (this.isSearching || !this.searchKeyword.trim()) return;
        this.isSearching = true;
        this.hasSearched = false;
        
        try {
          if (this.searchMode === 'local') {
            await this.searchLocal();
          } else {
            await this.searchNetwork();
          }
        } finally {
          this.isSearching = false;
          this.hasSearched = true;
        }
      },
      
      async searchLocal() {
        const keyword = this.searchKeyword.toLowerCase();
        this.localResults = this.chatList.filter(chat => 
          chat.name.toLowerCase().includes(keyword)
        );
      },
      
      async searchNetwork() {
		  // this.networkResults=[
			 //  {
			 //     id: 123456,
			 //     name: "王老师",
			 //     avatar: "/static/teacher.jpg",
			 //     roleType: 2 // 辅导员
			 //   }
		  // ]
       if (!this.searchKeyword.trim()) {
               uni.showToast({ title: '请输入搜索内容', icon: 'none' });
               return;
             }
       
             try {
               const res = await uni.request({
                 url: methodY.addr+'/api/userInfo/search',
                 data: { keyword: this.searchKeyword },
                 method: 'GET'
               });
			   console.log(res)
               this.networkResults = this.formatResults(res.data);
             } catch (e) {
               uni.showToast({ title: '搜索失败', icon: 'none' });
               console.error(e);
             } finally {
               this.loading = false;
             }
           },
      
      // 格式化数据
          formatResults(data) {
            return data.map(item => ({
              id: item.id,
              name: item.name,
              avatar: item.avatar || '/static/default-avatar.png',
              roleType: Number(item.roleType) || 1
            }));
          },
      // 打开搜索
      openSearch() {
        this.showSearchModal = true;
        this.searchKeyword = '';
        this.localResults = [];
        this.networkResults = [];
        this.isSearching = false; // 是否正在搜索
        this.hasSearched = false; // 是否已完成搜索
      },
      
      // 关闭搜索
      closeSearch() {
        this.showSearchModal = false;
      },
      
      // 打开聊天记录
      searchChat() {
        this.searchChatModel = true;
        this.keyword = '';
        this.searching = false;
        this.searched = false;
        this.searchResults = [];
      },
      
      // 关闭聊天记录搜索
      closeSearchChat() {
        this.searchChatModel = false;
      },
      
      // 执行搜索
      async startSearch() {
        if (!this.keyword.trim()) {
          uni.showToast({ title: '请输入搜索内容', icon: 'none' });
          return;
        }
        if (!this.selectedChat) {
          uni.showToast({ title: '请选择聊天人', icon: 'none' });
          return;
        }
        this.loading = true;
        this.searched = true;
        
        try {
          const keyword = this.keyword.toLowerCase();
          this.searchResults = this.selectedChat.messages.filter(msg => 
            msg.msg.toLowerCase().includes(keyword)
          );
          
          // 按时间倒序排序
          this.searchResults.sort((a, b) => {
            return new Date(b.timestamp) - new Date(a.timestamp);
          });
        } finally {
          this.loading = false;
        }
      },
      
      // 选中消息
      selectMessage(messageId) {
        this.scrollToBottom(messageId);
        this.$emit('message-selected', {
          chatId: this.selectedChat.id,
          messageId: messageId
        });
      },
      
      // 高亮关键词
      highlightKeyword(text) {
        if (!this.keyword) return text;
        const regex = new RegExp(this.keyword, 'gi');
        return text.replace(regex, match => 
          `<span style="background-color:#FFF9C4;color:#333;">${match}</span>`
        );
      },
      
      // 格式化分组日期
      formatGroupDate(dateStr) {
        const today = new Date().toISOString().split('T')[0];
        const yesterday = new Date(Date.now() - 86400000).toISOString().split('T')[0];
        
        if (dateStr === today) return '今天';
        if (dateStr === yesterday) return '昨天';
        
        // 格式化为 "2024年2月20日"
        const [year, month, day] = dateStr.split('-');
        return `${year}年${month}月${day}日`;
      },
      
      // 格式化消息时间
      formatTime(timestamp) {
        // 假设timestamp格式为 "2024-2-20 14:30"
        if (!timestamp.includes(' ')) return '';
        
        const timePart = timestamp.split(' ')[1];
        const [hour, minute] = timePart.split(':');
        return `${hour}:${minute}`;
      },
      
      getCurrentTime() {
        const now = new Date();
        const year = now.getFullYear();
        const month = (now.getMonth() + 1).toString().padStart(2, '0');
        const day = now.getDate().toString().padStart(2, '0');
        const hours = now.getHours().toString().padStart(2, '0');
        const minutes = now.getMinutes().toString().padStart(2, '0');
        const seconds = now.getSeconds().toString().padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
    }
};
</script>

<style lang="scss">
.container {
  display: flex;
}
.sidebar {
  width: 20%;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #f8f8f8;
}

.header-title {
  font-size: 18px;
  flex: 1; /* 让标题占据剩余空间 */
}

.header-right {
  display: flex;
  align-items: center;
}

.search-icon {
  width: 20px;
  height: 20px;
}
.chat-list {
  flex: 1;
  overflow-y: auto;
}

/* 聊天项容器 */
.chat-item {
  display: flex;
  padding: 20rpx;
  align-items: center;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.1); /* 默认下划线 */
  transition: background-color 0.3s;
  /* 头像样式 */
  
  /* 头像容器（相对定位） */
  .avatar-container {
    position: relative;
    width: 80rpx;
    height: 80rpx;
    margin-right: 20rpx;
  }
  
  /* 头像样式 */
  .avatar {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    margin-right: 20rpx;
    flex-shrink: 0; /* 防止头像被压缩 */
  }
  
  /* 红点样式 */
  .red-dot {
    position: absolute;
    top: -4rpx;
    right: -4rpx;
    width: 16rpx;
    height: 16rpx;
    background-color: #ff4d4f;
    border-radius: 50%;
    border: 2rpx solid #fff; /* 白色边框增加对比度 */
  }
 /* 删除按钮样式 */
 .delete-btn {
   position: absolute;
   right: 16px; /* 与右侧间距 */
   width: auto; /* 宽度自适应 */
   min-width: 64px; /* 最小宽度 */
   height: 32px; /* 固定高度 */
   background: #FF3B30;
   color: white;
   display: flex;
   justify-content: center;
   align-items: center;
   border-radius: 16px; /* 完全圆角 */
   padding: 0 12px; /* 左右内边距 */
   font-size: 14px;
   font-weight: 500;
   box-shadow: 0 2px 6px rgba(255, 59, 48, 0.3); /* 红色阴影 */
   transition: all 0.2s ease; /* 平滑过渡 */
 }
 
 /* 点击效果 */
 .delete-btn:active {
   background: #E53935;
   transform: scale(0.95); /* 按压缩小效果 */
   box-shadow: 0 1px 3px rgba(255, 59, 48, 0.2); /* 点击时阴影减小 */
 } 
}

/* 最后一个对话项不需要下划线 */
.chat-item.last-item {
  border-bottom: none;
}
/* 选中状态 */
.chat-item.selected {
  background-color:rgba(0,0,0,0.05); /* 选中时的背景色 */
}

/* 右侧内容区 */
.chat-content {
  flex: 1;
  min-width: 0; /* 关键！解决flex布局下的溢出问题 */
}

/* 用户名（单行省略） */
.chat-name {
  font-size: 32rpx;
  color: #333;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 最后消息（单行省略） */
.last-message {
  font-size: 26rpx;
  color: #999;
  margin-top: 6rpx;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
/* 身份标识（右侧） */
.identity-badge {
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 16rpx; /* 调整到右侧间距 */
  font-size: 24rpx;
  color: white;
  flex-shrink: 0;
  position: absolute;
  right: 24rpx; /* 固定在右侧 */
}

/* 不同身份的颜色样式 */
.role-1 { /* 学生 */
  background-color: #67C23A;
}
.role-2 { /* 辅导员 */
  background-color: #409EFF;
}
.role-3 { /* 咨询师 */
  background-color: #E6A23C;
}
/* 底部用户面板 */
.user-panel {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 24rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 72rpx;
  height: 72rpx;
  border-radius: 50%;
  margin-right: 16rpx;
}

.user-name {
  font-size: 28rpx;
  color: #333;
}

.settings-icon {
  width: 40rpx;
  height: 40rpx;
}

.chat-window {
  width: 80%;
  display: flex;
  flex-direction: column;
}

.messages {
   background-color: rgba(0,0,0,0.05);
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

/* 重置基础样式 */
.message-container {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  margin-bottom: 20px;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 消息容器 */
.message-container {
 max-height: 300px;
 display: flex;
 margin-top: 1rex;
 padding: 0 ;
 width: 100%;
 margin-left: auto;
 margin-right: auto;
}
/* 选中状态样式 */
.message-container.selected {
  box-shadow: 0 0 0 4rpx rgba(255, 255, 255, 0.8); /* 白色边框 */
  transform: scale(1.02); /* 轻微放大效果 */
  position: relative;
  z-index: 1; /* 确保选中项在上层 */
}

/* 头像系统 */
.avatar {
 background-color: rgba(0, 0, 0, 0.1);
 width: 2.5rem;    /* 头像尺寸相对单位 */
 height: 2.5rem;   /* 保持宽高比 */
}
/* 水平排列菜单 */
.horizontal-menu {
  background-color: #07c160;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  padding: 4px 0;
  margin-top: 4px;
  background: transparent;
  box-shadow: none;
}

.horizontal-menu .menu-item {
  padding: 6px 12px;
  margin: 0 4px;
  background: #fff;
  border-radius: 15px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.2);
  font-size: 12px;
  white-space: nowrap;
}

.horizontal-menu .menu-item:active {
  background: #f0f0f0;
}

/* 对方消息菜单对齐 */
.left-content .horizontal-menu {
  justify-content: flex-start;
  padding-left: 12px;
}

/* 自己消息菜单对齐 */
.right-content .horizontal-menu {
  justify-content: flex-end;
  padding-right: 12px;
}
/* 消息内容区域 */
.message-content {
  display: flex;
  flex-direction: column;
  max-width: 60%;
  min-width: 120px;
}

/* 左侧消息样式 */
.other-message {
  justify-content: flex-start;
   margin-left: auto; /* 增强右侧定位 */
  .left-avatar {
    margin-right: 1rem;
  }
  .left-content {
	//background-color: #07c160;
	
    max-width: calc(min(70%, 40rem)); /* 结合固定最大值和百分比 */
  }
  

  .left-bubble {
	min-width: 120px;
    position: relative;
    background: #fff;
	// border-radius: 0.7rem 0.7rem 0.7rem 0.7rem; /* 统一圆角单位 */
	// padding: 0.75rem 1.25rem;        /* 与左侧统一内边距 */
    border-radius: 0.8rem 1rem 1rem 1rem;
    padding: 0.75rem 1.25rem;
    color: #333;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	 font-size: clamp(0.875rem, 2vw, 1rem); /* 响应式字体 */
    word-break: break-word;
    hyphens: auto;

    /* 气泡箭头 */
    &::after {
      content: '';
      position: absolute;
      left: -0.8rem;
      top: 0.75rem;
      border: 0.5rem solid transparent;
      border-right-color: #fff;
      filter: drop-shadow(-2px 0 1px rgba(0,0,0,0.1));
    }
  }
}



/* 响应式适配 */
@media (min-width: 768px) {
  .message-container {
    padding: 0 5%;
  }

  .left-bubble {
    max-width: 60%;
  }
}

@media (min-width: 1200px) {
  .message-container {
    padding: 0 5%;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .other-message .left-bubble {
    background: #2d2d2d;
    color: #fff;
    box-shadow: 0 2px 8px rgba(0,0,0,0.3);
    
    &::after {
      border-right-color: #2d2d2d;
    }
  }
  
  .message-time {
    color: #999;
  }
}

/* 浏览器兼容处理 */
@supports not (hyphens: auto) {
  .left-bubble {
    word-break: break-all;
  }
}

@supports not (gap: 1rem) {
  .message-time {
    margin-right: 0.25rem;
    &::after {
      content: '•';
      margin-left: 0.25rem;
    }
  }
}


/* 右侧消息样式 - 响应式 */
.self-message {
  justify-content: flex-end;
  margin-left: auto; /* 增强右侧定位 */

  .right-avatar {
    margin-left: 1rem; /* 改用rem单位 */
  }
  
  .right-content {
    max-width: calc(min(70%, 40rem)); /* 结合固定最大值和百分比 */
  }

  .right-bubble {
    background: #95ec69;
    border-radius: 0.7rem 0.7rem 0.7rem 0.7rem; /* 统一圆角单位 */
    padding: 0.75rem 1.25rem;        /* 与左侧统一内边距 */
    position: relative;
    font-size: clamp(0.875rem, 2vw, 1rem); /* 响应式字体 */
    color: #2c2c2c;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    word-break: break-word;
    hyphens: auto;

    /* 响应式气泡箭头 */
    &::after {
      content: '';
      position: absolute;
      right: -0.8rem;        /* rem单位 */
      top: 0.75rem;
      border: 0.5rem solid transparent;
      border-left-color: #95ec69;
       filter: drop-shadow(2px 0 1px rgba(0,0,0,0.1));
    }

    /* 小屏幕适配 */
    @media (max-width: 480px) {
      border-radius: 0.75rem 0 0.75rem 0.75rem;
      &::after {
        right: -0.5rem;
        border-width: 0.4rem;
      }
    }
  }
}

/* 消息气泡通用样式 */
.bubble {
  padding: 16rpx 20rpx;
  position: relative;
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);
}

/* 发送者信息 */
.sender-name {
  color: #666;
  font-size: 24rpx;
  margin-bottom: 8rpx;
  display: block;
}
/* 时间戳和状态 */
.timestamp {
  //background-color: #007AFF;
  font-size: 0.75rem;
  color: #666;
  margin-top: 0.5rem;
  display: flex;
  align-items: center;
  gap: 0.25rem;
}
.status-wrapper {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 8rpx;
}
.status-icon {
  font-size: 24rpx;
  color: #666;
  margin-left: 8rpx;
}

.editor-box{
	background-color: #f0f0f0;
	display: flex;
	justify-content: center;
	align-items: center;
	height: 25%;
     padding: 10px;
}
/* 容器布局 */
.editor-container {
  background-color: white;
  display: flex;
  border-radius: 16rpx;
  padding: 1%;
  width: 80%;
  height: 100%;
  flex-direction: column;
  border: 1rpx solid rgba(0,0,0,0.1);
  box-sizing: border-box;
  /* 添加阴影效果 */
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}
/* 上层编辑区域 */
.editor-content {
  box-sizing: border-box;
  flex: 1;
  .text-editor {
	height: 100%;
    width: 100%;
    font-size: 16px;
  }
}
/* 下层操作栏 */
.editor-actions {
   box-sizing: border-box;
   background-color: #f5f5f5;
   padding: 10px;
   height: auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* 按钮组容器 */
  .action-group {
	width: 80%;            /* 占满父容器宽度 */
	gap: 20rpx;             /* 元素间距 */
	padding-left: 0;        /* 清除默认内边距 */
    height: 100%;
    display: flex;
    align-items: center;
  }
  
  /* 主按钮样式（带文字） */
  .icon-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 8rpx 16rpx;
    border-radius: 12rpx;
    transition: all 0.2s ease;
  }
  
  /* 图标样式 */
  .action-icon {
    width: 40rpx;
    height: 40rpx;
    margin-bottom: 6rpx;
  }
  
  /* 按钮文字 */
  .btn-text {
    font-size: 24rpx;
    color: #666;
    line-height: 1.2;
  }
  
  /* 扩展功能菜单容器 */
  .more-actions {
    display: flex;
    gap: 32rpx; /* 按钮间距 */
    align-items: center;
  }
  
  /* 扩展按钮（无文字） */
  .more-actions .icon-btn {
    padding: 12rpx;
  }
  
  .more-actions .action-icon {
    margin-bottom: 0;
  }
  
  /* 交互效果 */
  .icon-btn:active {
    background-color: rgba(0, 0, 0, 0.08);
    transform: scale(0.96);
  }
  
  /* 当前选中状态（可选） */
  .icon-btn.active {
    background-color: rgba(0, 122, 255, 0.1);
  }

  .send-btn {
	display: flex;
	justify-content: center;
	align-items: center; 
    min-width: 52px;
    height: 100%;
    color: rgba(0, 0, 0, 0.5);
    border-radius: 15%;
    &.disabled {
      background: #ccc;
      opacity: 0.7;
    }
  }
}
 .search-chat-folder-modal{
	padding: 30rpx;
	box-sizing: border-box;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 1; /* 确保模态框位于最上层 */
	/* 初始状态为隐藏 */
	transform: translateY(100%);
	opacity: 0;
	transition:  opacity 0.5s ease; /* 添加过渡效果 */
	.modal-content{
		background-color: white;
		padding: 20px;
		border-radius: 30px;
		width: 600px;
		height: 350px; /* 最大高度 */
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
		display: flex;
		flex-direction: column; /* 纵向布局 */
		position: relative;
		 /* 搜索栏样式 */
		 .search-bar {
		   display: flex;
		   align-items: center;
		   background-color: rgba(0, 0, 0, 0.08);
		   border-radius: 40rpx;
		   padding: 0 20rpx;
		   box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
		 }
		 
		 .search-input {
		   flex: 1;
		   height: 80rpx;
		   padding: 0 20rpx;
		   font-size: 28rpx;
		 }
		 
		 .search-icon {
		   width: 40rpx;
		   height: 40rpx;
		 }
		 /* 禁用状态样式 */
		 .icon-disabled {
		   opacity: 0.5;
		   pointer-events: none;
		 }
		 
		 .search-input:disabled {
		   background-color: #f5f5f5;
		   color: #999;
		 }
		.result-container {
		  flex: 1;
		  padding: 10px;
		  overflow-y: auto;
		}
		
		.date-group {
		  margin-bottom: 20px;
		}
		
		.date-title {
		  font-size: 14px;
		  color: #999;
		  padding: 5px 0;
		  margin-bottom: 10px;
		  border-bottom: 1px solid #eee;
		}
		
		// .message-item {
		//   margin-bottom: 12px;
		// }
		/* 优化选中效果 */
		.message-item {
		  padding: 12px;
		  border-radius: 8px;
		  margin-bottom: 8px;
		  transition: all 0.2s;
		}
		
		.message-item:active {
		  background-color: #f0f0f0;
		  transform: scale(0.98);
		}
		.message-content {
		  background-color: #f5f5f5;
		  border-radius: 8px;
		  padding: 10px;
		  max-width: 80%;
		}
		
		.self-message {
		  background-color: #e3f2fd;
		  margin-left: auto;
		}
		
		.message-header {
		  display: flex;
		  justify-content: space-between;
		  margin-bottom: 5px;
		}
		
		.sender {
		  font-weight: bold;
		  font-size: 15px;
		}
		
		.time {
		  font-size: 12px;
		  color: #999;
		}
		
		.message-text {
		  font-size: 14px;
		  line-height: 1.5;
		  display: -webkit-box; /* 使用弹性盒子布局 */
		  -webkit-line-clamp: 3; /* 限制显示行数 */
		   -webkit-box-orient: vertical; /* 垂直排列 */
		   overflow: hidden; /* 隐藏超出部分 */
		   text-overflow: ellipsis; /* 超出显示省略号 */
		   word-break: break-word; /* 允许单词内断行 */
		}
		
		.loading, .empty, .initial-hint {
		  display: flex;
		  justify-content: center;
		  align-items: center;
		  height: 100%;
		  color: #999;
		}
		
		
	}
}

.search-chat-folder-modal.slide-in {
    transform: translateY(0); /* 滑入 */
    opacity: 1; /* 完全可见 */
}
.search-chat-folder-modal.slide-out {
    transform: translateY(100%); /* 滑出 */
    opacity: 0; /* 完全透明 */
}


.search-folder-modal{
	padding: 30rpx;
	box-sizing: border-box;
  	position: fixed;
  	bottom: 0;
  	left: 0;
  	right: 0;
  	width: 100%;
  	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
  	display: flex;
  	justify-content: center;
	align-items: center;
  	z-index: 1; /* 确保模态框位于最上层 */
  	/* 初始状态为隐藏 */
  	transform: translateY(100%);
  	opacity: 0;
  	transition:  opacity 0.5s ease; /* 添加过渡效果 */
  	.modal-content{
  		background-color: white;
  		padding: 20px;
  		border-radius: 30px;
  		width: 600px;
  		height: 350px; /* 最大高度 */
  		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  		display: flex;
  		flex-direction: column; /* 纵向布局 */
  		position: relative;
		/* 标签页样式 */
		.search-tabs {
		  display: flex;
		  margin-bottom: 24rpx;
		  border-bottom: 1px solid #eee;
		}
		
		.tab-item {
		  flex: 1;
		  text-align: center;
		  padding: 20rpx;
		  color: #666;
		  position: relative;
		}
		
		.tab-item.active {
		  color: #007AFF;
		  font-weight: bold;
		}
		
		.tab-item.active::after {
		  content: '';
		  position: absolute;
		  bottom: -1px;
		  left: 25%;
		  right: 25%;
		  height: 4rpx;
		  background-color: #007AFF;
		  border-radius: 4rpx;
		}
		/* 搜索栏样式 */
		.search-bar {
		  display: flex;
		  align-items: center;
		  background-color: rgba(0, 0, 0, 0.08);
		  border-radius: 40rpx;
		  padding: 0 20rpx;
		  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
		}
		
		.search-input {
		  flex: 1;
		  height: 80rpx;
		  padding: 0 20rpx;
		  font-size: 28rpx;
		}
		
		.search-icon {
		  width: 40rpx;
		  height: 40rpx;
		}
		/* 禁用状态样式 */
		.icon-disabled {
		  opacity: 0.5;
		  pointer-events: none;
		}
		
		.search-input:disabled {
		  background-color: #f5f5f5;
		  color: #999;
		}
		/* 搜索结果容器  */
		.result-container {
		  flex: 1; /* 占据剩余空间 */
		  min-height: 0; /* 修复flex容器溢出问题 */
		  overflow-y: auto; /* 允许内容滚动 */
		  padding: 20rpx;
		  background-color: #ffffff; /* 恢复白色背景 */
		  box-sizing: border-box;
		}
		
		/* 加载状态 */
		.loading-state {
		  display: flex;
		  flex-direction: column;
		  align-items: center;
		  justify-content: center;
		  padding: 40rpx 0;
		  color: #999;
		  font-size: 28rpx;
		}
		
		.loading-state text {
		  margin-top: 20rpx;
		}
		
		/* 对话项样式 */
		.chat-item {
		  display: flex;
		  align-items: center;
		  padding: 24rpx;
		  margin-bottom: 16rpx;
		  background-color: #f9f9f9;
		  border-radius: 12rpx;
		  transition: all 0.2s ease;
		}
		
		.chat-item:active {
		  background-color: #f0f0f0;
		  transform: scale(0.98);
		}
		
		.avatar {
		  width: 80rpx;
		  height: 80rpx;
		  border-radius: 50%;
		  margin-right: 20rpx;
		  object-fit: cover;
		  border: 1rpx solid #eee;
		}
		
		.chat-info {
		  flex: 1;
		  min-width: 0;
		}
		
		.chat-name {
		  font-size: 32rpx;
		  color: #333;
		  font-weight: 500;
		  display: block;
		  white-space: nowrap;
		  overflow: hidden;
		  text-overflow: ellipsis;
		}
		
		/* 空状态提示 */
		.empty-tips {
		  text-align: center;
		  padding: 60rpx 0;
		  color: #999;
		  font-size: 28rpx;
		  display: flex;
		  flex-direction: column;
		  align-items: center;
		}
		.empty-tips::before {
		  content: "";
		  display: block;
		  width: 120rpx;
		  height: 120rpx;
		  background-image: url('/static/empty-search.png');
		  background-size: contain;
		  background-repeat: no-repeat;
		  margin-bottom: 20rpx;
		  opacity: 0.6;
		}
		
		/* 不同搜索模式下的视觉区分 */
		[searchmode="local"] .chat-item {
		  border-left: 6rpx solid #07c160;
		}
		
		[searchmode="network"] .chat-item {
		  border-left: 6rpx solid #2979ff;
		}
		/* 容器样式 */
		.network-chat-item {
		  display: flex;
		  align-items: center;
		  padding: 20rpx 24rpx;
		  background-color: #fff;
		  border-radius: 16rpx;
		  margin-bottom: 16rpx;
		  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
		}
		
		/* 身份标识 */
		.identity-badge {
		  position: relative;
		  width: 44rpx;
		  height: 44rpx;
		  border-radius: 50%;
		  display: flex;
		  align-items: center;
		  justify-content: center;
		  margin-right: 20rpx;
		  font-size: 24rpx;
		  font-weight: 500;
		  color: white;
		  flex-shrink: 0;
		}
		
		.role-0 { background-color: #B2B2B2; } /* 未设置 */
		.role-1 { background-color: #4CAF50; }  /* 学生 */
		.role-2 { background-color: #2196F3; }   /* 辅导员 */
		.role-3 { background-color: #FF9800; }  /* 咨询师 */
		
		/* 头像样式 */
		.network-avatar {
		  width: 80rpx;
		  height: 80rpx;
		  border-radius: 12rpx;
		  margin-right: 20rpx;
		  background-color: #f5f5f5;
		}
		
		/* 信息区域 */
		.network-info {
		  flex: 1;
		  min-width: 0;
		}
		
		.name-line {
		  display: flex;
		  align-items: baseline;
		  margin-bottom: 6rpx;
		}
		
		.network-name {
		  font-size: 32rpx;
		  font-weight: 500;
		  color: #333;
		  margin-right: 16rpx;
		  overflow: hidden;
		  text-overflow: ellipsis;
		  white-space: nowrap;
		}
		
		.network-role {
		  font-size: 24rpx;
		  color: #999;
		  padding: 4rpx 12rpx;
		  background-color: #f5f5f5;
		  border-radius: 20rpx;
		}
		
		.network-id {
		  font-size: 24rpx;
		  color: #B2B2B2;
		}
		
		/* 操作按钮 */
		.network-action {
		  width: 64rpx;
		  height: 64rpx;
		  border-radius: 50%;
		  display: flex;
		  align-items: center;
		  justify-content: center;
		  //background-color: #F0F7FF;
		  transition: all 0.2s;
		}
		
		.network-action:active {
		  transform: scale(0.95);
		}
		
		.network-action.exists {
		  //background-color: #F5F5F5;
		}
		
		.action-icon {
		  width: 100%;
		  height: 100%;
		}
		
		/* 交互状态 */
		.network-chat-item:active {
		  background-color: #f9f9f9;
		}
	}
}

 /* 滑入效果 */
 .search-folder-modal.slide-in {
    transform: translateY(0); /* 滑入 */
    opacity: 1; /* 完全可见 */
  }
  /* 滑出效果 */
  .search-folder-modal.slide-out {
    transform: translateY(100%); /* 滑出 */
    opacity: 0; /* 完全透明 */
  }

</style>
